<script lang='ts'  setup>
import { reactive, ref, nextTick } from 'vue';
import type { FormInstance } from 'element-plus'
import api from '@/api'
import { ElMessage, ElMessageBox, FormRules } from 'element-plus';


// 查询条件
const query = reactive<{ state: number, userId?: string, userName?: string }>({
    state: 1,
})
// 重置查询表单
const queryFormRef = ref<FormInstance>()
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
// 页码
const pager = ref<{ pageSize: number, pageNum: number, total: number }>({ pageSize: 10, pageNum: 1, total: 0 })

// 用户列表
interface IUsers {
    userId?: number
    userName?: string
    userEmail?: string
    role?: number
    state?: number
    regTime?: Date
    lastLoginTime?: Date
}
let users = ref<IUsers[]>([])

// 发起查询用户
const handleQuery = async () => {
    try {
        const params = { ...query, ...pager.value }
        const { data: res } = await api.getUserListApi(params)
        pager.value = res.page
        users.value = res.list
    } catch (error) {
        console.log(error)
    }
}
handleQuery()

// 待删除用户列表
let checkedUserIds: number[] = []
// 删除用户
const handleDel = (row: number[]) => {
    ElMessageBox.confirm(
        '将要删除用户. 是否继续?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const { data: res } = await api.delUserApi(row)
            if (res) {
                ElMessage.success('操作成功')
                handleQuery()
            }
        })

}
// 选中行 变化
const handleSelectChange = (selection: IUsers[]) => {
    checkedUserIds = selection.map(item => item.userId) as number[]
}

// 批量删除用户
const handleBatchDel = async () => {
    if (checkedUserIds.length <= 0) {
        ElMessage.warning('请选择需要删除的行')
    } else {
        handleDel(checkedUserIds)
    }
}

// 新增用户

const dialogVisible = ref(false)
// 用户角色列表
const userRoles = ref<{ _id: string, roleName: string }[]>([])
const getUserRoles = async () => {
    const { data: res } = await api.getRolesListApi()
    userRoles.value = res
}
getUserRoles()

// 部门列表
const deptList = ref([])

const getDeptList = async () => {
    const { data: res } = await api.deptApi({}, 'get')
    deptList.value = res
}
getDeptList()

// 待新增用户
interface IWaitAddUser {
    userName?: string
    userEmail?: string
    emailSuffix?: string
    mobile?: string
    job?: number
    state?: number
    deptId?: number[]
    roleList?: []
}
const waitAddUser = ref<IWaitAddUser>({ state: 3, emailSuffix: '@qq.com' })

const addUserFormRef = ref<FormInstance>()
const handleClose = (formEl: FormInstance | undefined) => {
    ElMessageBox.confirm(
        '将要取消操作. 是否继续?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        .then(() => {
            dialogVisible.value = false
            formEl?.resetFields()
        }).catch(() => {
        })
}
// 是否为编辑模式
const isEditMode = ref(false)
// 提交用户信息
const addUserCommit = async () => {
    addUserFormRef.value?.validate(async (isValid: boolean) => {
        if (isValid) {
            const userDataRaw = JSON.parse(JSON.stringify(waitAddUser.value))
            userDataRaw.userEmail += userDataRaw.emailSuffix as string

            try {
                if (isEditMode.value) {
                    const { data: res } = await api.postAddUser(userDataRaw, 'put')
                    if (res) { ElMessage.success('已成功修改用户信息') }
                } else {
                    const { data: res } = await api.postAddUser(userDataRaw)
                    if (res) { ElMessage.success('用户创建成功') }
                }
                handleQuery()
                waitAddUser.value = { state: 3, emailSuffix: '@qq.com' }
                dialogVisible.value = false
                addUserFormRef.value?.resetFields()
            } catch (error) {

            }

        } else {
            ElMessage.warning('表单验证不合格')
        }
    })

}

// 编辑用户信息
const handleEdit = (row: IWaitAddUser) => {
    isEditMode.value = true
    dialogVisible.value = true
    const splitMail = row.userEmail?.split('@')
    nextTick(() => {
        Object.assign(waitAddUser.value, row)
        if (splitMail) {
            waitAddUser.value.userEmail = splitMail[0]
            waitAddUser.value.emailSuffix = '@' + splitMail[1]
        }
    })
}


const addUserRules = reactive<FormRules>({
    userName: [
        { required: true, message: '请输入用户姓名' }
    ],
    userEmail: [
        { required: true, message: '请输入用户邮箱' },
    ],
    deptId: [
        { required: true, message: '请选择用户所属部门' }
    ],
    mobile: [{ pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
})

// 分页切换
const handlePageChange = (val: number) => {
    pager.value.pageNum = val
    handleQuery()
}




// 表格列
const tableColumns = reactive([
    { prop: 'userId', label: '用户ID' },
    { prop: 'userName', label: '用户名称' },
    { prop: 'userEmail', label: '用户邮箱' },
    { prop: 'role', label: '用户角色', formatter(row: [], col: [], val: number) { return { 0: '管理员', 1: '普通用户' }[val] } },
    { prop: 'state', label: '用户状态', formatter(row: [], col: [], val: number) { return { 1: '在职', 2: '离职', 3: '试用期' }[val] } },
    { prop: 'createTime', label: '注册时间', },
    { prop: 'lastLoginTime', label: '最后登陆时间' },
])


</script>

<template>
    <div id='UserManage'>
        <div class=" p-[20px] pb-0   card overflow-hidden ">
            <!-- 条件查询表单区域 -->
            <el-form inline :model="query" ref="queryFormRef">
                <el-form-item label="用户ID" prop="userId">
                    <el-input placeholder="请输入用户ID" v-model.trim="query.userId" />
                </el-form-item>
                <el-form-item label="用户名称" prop="userName">
                    <el-input placeholder="请输入用户名称" v-model.trim="query.userName" />
                </el-form-item>
                <el-form-item label="状态" prop="select">
                    <el-select v-model="query.state">
                        <el-option :value="0" label="所有" />
                        <el-option :value="1" label="在职" />
                        <el-option :value="2" label="离职" />
                        <el-option :value="3" label="试用期" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="danger" @click="resetForm(queryFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class=" h-[20px] bg-slate-50"></div>
        <!-- 表单content -->
        <div class=" card ">
            <!-- 操作区域 -->
            <div class=" p-[20px]">
                <el-button type="primary" @click="dialogVisible = true; isEditMode = false">新增</el-button>
                <el-button type="danger" @click="handleBatchDel">批量删除</el-button>
            </div>
            <!-- 表格正文 -->
            <el-table :data="users" max-height="370.5px" @selection-change="handleSelectChange">
                <el-table-column type="selection" />
                <!-- 循环渲染表格列 -->
                <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop"
                    :label="column.label" :formatter="column.formatter" />
                <el-table-column label="操作" width="80px" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" icon="Edit" @click="handleEdit(scope.row)" circle />
                        <el-button type="danger" icon="Delete" @click="handleDel([scope.row.userId])" circle />
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 新增用户模态框 -->
        <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑用户信息' : '创建用户'" width="30%" :show-close="false">

            <el-form :model="waitAddUser" size="default" label-width="auto" :rules="addUserRules" ref="addUserFormRef">
                <el-form-item label="用户名" prop="userName">
                    <el-input placeholder="请输入用户名称" v-model.trim="waitAddUser.userName" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input placeholder="请输入用户邮箱" v-model="waitAddUser.userEmail">
                        <template #append>
                            <el-select v-model="waitAddUser.emailSuffix">
                                <el-option value="@163.com" />
                                <el-option value="@qq.com" />
                                <el-option value="@gmail.com" />
                                <el-option value="@126.com" />
                            </el-select>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input placeholder="请输入用户手机号" v-model.number="waitAddUser.mobile" maxlength="11" />
                </el-form-item>
                <el-form-item label="岗位" prop="job">
                    <el-input placeholder="请输入用户岗位" v-model.trim="waitAddUser.job" />
                </el-form-item>
                <el-form-item label="状态" prop="state" class=" select-none">
                    <el-select v-model="waitAddUser.state">
                        <el-option :value="1" label="在职" />
                        <el-option :value="2" label="离职" />
                        <el-option :value="3" label="试用期" />
                    </el-select>
                </el-form-item>
                <el-form-item label="系统角色" prop="roleList">
                    <el-select v-model="waitAddUser.roleList" multiple placeholder="请选择系统角色" style="width: 100%">
                        <el-option v-for="item in userRoles" :key="item._id" :label="item.roleName" :value="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="deptId">
                    <el-cascader :options="deptList" v-model="waitAddUser.deptId" placeholder="请选择用户所属部门"
                        style="width: 100%;" :props="{
                            checkStrictly: true,
                            label: 'deptName',
                            value: '_id'
                        }" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose(addUserFormRef)" size="default">取消</el-button>
                    <el-button type="primary" @click="addUserCommit" size="default">提交</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 分页器 -->
        <el-pagination background layout="prev, pager, next" :total="pager.total" @current-change="handlePageChange"
            class=" bg-white p-[20px] justify-center" />
    </div>
</template>
